<?php
/**
*
* @filename 会员管理
*/
namespace app\admin\controller;

use app\admin\model\OrderChangeLog;
use think\Controller;
use app\admin\model\Member as Members;
use app\admin\model\Putlog;
use app\admin\model\Order;
use think\Db;
use think\Model;

class Member extends Common
{
    private $cModel;   //当前控制器关联模型
    
    public function _initialize()
    {
        parent::_initialize();
        $this->cModel = new Members;   //别名：避免与控制名冲突
    }
    
    public function index()
    {
        $where = [];
        if (isset($_GET['is_check']) && input('get.is_check')!=-1){
            $where['is_check'] = ['eq', input('get.is_check')];
        }
        if (isset($_GET['is_disable']) && input('get.is_disable')!=-1){
            $where['is_disable'] = ['eq', input('get.is_disable')];
        }
        if (input('get.start_date') && input('get.end_date')){ // 开始/结束同时存在
            $where['create_time'] = ['between time', [strtotime(input('get.start_date').' 00:00:00'),strtotime(input('get.end_date').' 23:59:59')]];
        }
        if (input('get.search')){
            $where['username|email|mobile'] = ['like', '%'.input('get.search').'%'];
        }
        if (input('get.invite')){
            $where['invite'] = ['eq', input('get.invite')];
        }
        if (input('get._sort')){
            $order = explode(',', input('get._sort'));
            $order = $order[0].' '.$order[1];
        }else{
            $order = 'id desc';
        }

		if(input('get.down')){
			$tableHeader = ['姓名','手机号','创建时间','身份证','性别','余额','推荐人','实名','状态','最近登录'];
			$dataList = $this->cModel->where($where)->order($order)->select();
			$data = [];
			foreach($dataList as $k=>$v){
				$data[$k]['usernmae'] =  $v['username'];
				$data[$k]['mobile'] =  $v['mobile'];
				$data[$k]['create_time'] =  $v['create_time'];
				$data[$k]['certificate'] =  $v['certificate'].' ';
				$data[$k]['sex'] =  $v['sex'];
				$data[$k]['money'] =  $v['money'];
				$data[$k]['parent_name'] =  $this->cModel->where(['id'=>$v['parentId']])->value('username');
                                $data[$k]['mobile'] =  $this->cModel->where(['id'=>$v['parentId']])->value('mobile');
				$data[$k]['is_check'] =  $v['is_check'] == 1 ? '已认证' : '未认证';
				$data[$k]['is_disable'] =  $v['is_disable'] == 1 ? '正常' : '黑名单';
				$data[$k]['last2_time'] =  $v['last2_time'] ? date('Y-m-d H:i:s', $v['last2_time']) : '';
			}
			ToPHPEXECL($tableHeader,$data,'会员列表');
		}

        $dataList = $this->cModel->where($where)->order($order)->paginate('', false, page_param());
		foreach($dataList as &$row){
			$row['parent_name'] = $this->cModel->where(['id'=>$row['parentId']])->value('username');
                        $row['parent_mobile'] = $this->cModel->where(['id'=>$row['parentId']])->value('mobile');
		}
		unset($row);
        $this->assign('dataList', $dataList);
        return $this->fetch();
    }



	
	public function create(){
        if (request()->isPost()){
            Db::startTrans();
            try{
                $data = input('post.');
                $result = $this->cModel->validate(CONTROLLER_NAME.'.add')->allowField(true)->save($data);
                $uid = $this->cModel->getLastInsID();
                // 提交事务
                if ($result && $uid){
                    Db::commit();
                    return ajaxReturn(lang('action_success'), url('index'));
                }else{
                    return ajaxReturn($this->cModel->getError());
                }
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return ajaxReturn($e->getMessage());
            }
        }else{
            return $this->fetch('create');
        }
	}

    public function edit($id)
    {
        if (request()->isPost()){
            $data = input('post.');
            if ($data['actions'] == 'password'){    //修改密码
                if ( $data['id'] != UID ){          //修改他人密码需验证旧密码
                    $oldData = $this->cModel->where(['id' => $data['id'], 'password' => md5($data['oldpassword'])])->find();
                    if (empty($oldData)){
                       return ajaxReturn(lang('oldpassword_val'));
                    }
                }
                $result = $this->cModel->validate(CONTROLLER_NAME.'.password')->allowField(true)->save($data, $data['id']);
            }elseif ($data['actions'] == 'avatar'){   //修改头像
                $where = ['id' => $data['id']];
                unset($data['actions']);
                $result = $this->cModel->allowField(true)->where($where)->update($data);
            }elseif ($data['actions'] == 'infos'){   //修改附加信息
                $where = ['id' => $data['id']];
                unset($data['actions']);
                $result = $this->cModel->allowField(true)->where($where)->update($data);
            }else{   //修改信息
                if (count($data) == 2){
                    foreach ($data as $k =>$v){
                        $fv = $k!='id' ? $k : '';
                    }
                    $result = $this->cModel->validate(CONTROLLER_NAME.'.'.$fv)->allowField(true)->save($data, $data['id']);
                }else{
                    $result = $this->cModel->validate(CONTROLLER_NAME.'.edit')->allowField(true)->save($data, $data['id']);
                }
            }
            if ($result){
                return ajaxReturn(lang('action_success'), url('index'));
            }else{
                return ajaxReturn($this->cModel->getError());
            }
        }else{
            if ($id > 0){
                $data = $this->cModel->get($id);
                $this->assign('data', $data);
                return $this->fetch();
            }
        }
    }
	//账户明细
	public function account($id){
	    
		$PutModel = new Putlog();
		$where = [];
		$where['uid'] = intval($id);
		
        if (isset($_GET['status']) && input('get.status')!=-1){
            $where['status'] = ['eq', input('get.status')];
        }
        if (input('get.type')){
            $where['type'] = ['eq', input('get.type')];
        }
        if (input('get.start_date') && input('get.end_date')){ // 开始/结束同时存在
            $where['create_time'] = ['between time', [strtotime(input('get.start_date').' 00:00:00'),strtotime(input('get.end_date').' 23:59:59')]];
        }
        if (input('get.search')){
            $where['username|email|mobile'] = ['like', '%'.input('get.search').'%'];
        }
        if (input('get._sort')){
            $order = explode(',', input('get._sort'));
            $order = $order[0].' '.$order[1];
        }else{
            $order = 'id desc';
        }
		if(input('get.down')){
			$tableHeader = ['流水号','类型','金额','状态','时间'];
			$dataList = $PutModel->where($where)->order($order)->select();
			$data = [];
			foreach($dataList as $k=>$v){
				$data[$k]['order'] =  $v['order']; 
				$data[$k]['type'] =  $v['type']; 
				$data[$k]['money'] =  $v['money']; 
				$data[$k]['status'] =  $v['status']; 
				$data[$k]['create_time'] =  $v['create_time']; 
			}
			ToPHPEXECL($tableHeader,$data,'账户明细');
		}
		$dataList = $PutModel->where($where)->order($order)->paginate('', false, page_param());
		$this->assign('dataList', $dataList);
		$this->assign('id', $id);
		return $this->fetch();
	}
	
    public function delete()
    {
        if (request()->isPost()){
            $id = input('id');
            if (isset($id) && !empty($id)){
                Db::startTrans();
                try{
                    $id_arr = explode(',', $id);   //用户数据
					$rechModel = new \app\admin\model\Recharge;
					$cashModel = new \app\admin\model\Getcash;
                    $where1 = [ 'user_id' => ['in', $id_arr] ];
                    $where2 = [ 'id' => ['in', $id_arr] ];
                    $result = $this->cModel->where($where2)->delete();   //删除主表数据
                    $result2 = $rechModel->where($where1)->delete();   //删除充值记录
                    $result3 = $rechModel->where($where1)->delete();   //删除提现记录
                    // 提交事务
                    if ($result){
                        Db::commit();
                        return ajaxReturn(lang('action_success'), url('index'));
                    }else{
                        return ajaxReturn($this->cModel->getError());
                    }
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return ajaxReturn($e->getMessage());
                }
            }
        }
    }
	
	public function reward(){
		
		$orderModel = new Order();
		$where['agentid'] = ['>',0];
		if(isset($_GET['status']) && input('get.status')!=-1){
			$where['a.status'] = ['eq',input('get.status')];
		}
		if(input('get.search')){
			$where['a.order_sn|a.money|b.username|b.mobile'] = ['like', '%'.input('get.search').'%'];
		}
        if (input('get._sort')){
            $order = explode(',', input('get._sort'));
            $order = $order[0].' '.$order[1];
        }else{
            $order = 'id desc';
        }
		if(input('get.down')){
			$tableHeader = ['奖励人','手机号','订单号','订单金额','奖励金额','状态','创建时间'];
			$dataList = $orderModel
						->field('a.*,b.username,b.mobile')
						->alias('a')
						->join('tf_member b','a.agentid=b.id','LEFT')
						->where($where)
						->order($order)
						->select();
			$data = [];
			foreach($dataList as $k=>$v){
				$data[$k]['username'] =  $v['username']; 
				$data[$k]['mobile'] =  $v['mobile']; 
				$data[$k]['order_sn'] =  $v['order_sn']; 
				$data[$k]['money'] =  $v['money']; 
				$data[$k]['agentMoney'] =  $v['agentMoney']; 
				$data[$k]['status'] =  $v['status']; 
				$data[$k]['create_time'] =  $v['create_time']; 
			}

			ToPHPEXECL($tableHeader,$data,'奖励列表');
		}
		$dataList = $orderModel
					->field('a.*,b.username,b.mobile')
					->alias('a')
					->join('tf_member b','a.agentid=b.id','LEFT')
					->where($where)
					->order($order)
					->paginate('', false, page_param());			
		$this->assign('dataList', $dataList);
		return $this->fetch();
	}


    private function memberRelation()
    {
        $model = db::name('b_gx');
        $sql="SELECT abm.user_id,tm.parentId,tm.username,tm.mobile,abm.grade,
                (
                CASE abm.grade
                    WHEN 1 THEN
                    '高级会员'
                    WHEN 2 THEN
                    '销售顾问'
                    WHEN 3 THEN
                    '业务经理'
                    WHEN 4 THEN
                    '渠道总监'
                    ELSE
                    ''
                END
                ) as name
                from an_b_member abm inner join tf_member tm on tm.id=abm.user_id
                where abm.user_id in
                (
                SELECT gx.user_id from tf_member tm inner JOIN tf_b_gx  gx on tm.id=gx.user_id
                WHERE gx.parent_id=14 and gx.gx=1
                )
                 and abm.grade>=2
                ORDER BY abm.user_id";   //gx.gx=1 就是直属下级 !=1 就是非直属下级
        $dataList = db::query($sql);
        $tableHeader = ['会员ID','上级ID','姓名','电话','等级','团队人数'];
        $data = [];
        foreach($dataList as $k=>$v){
            $data[$k]['user_id'] =  $v['user_id'];
            $data[$k]['parentId'] =  $v['parentId'];
            $data[$k]['username'] =  $v['username'];
            $data[$k]['mobile'] =  $v['mobile'];
            $data[$k]['name'] =  $v['name'];
            $data[$k]['member_count'] =$model->where(['parent_id'=>$v['user_id']])->count();
        }
        ToPHPEXECL($tableHeader,$data,'王艳红直推会员关系');

       exit;
    }

    //会员订单详情
    public  function memberOrderDetailList($uid){
        $order_model = new Order();
        $m_model = new \app\admin\model\Member();
        $user_info = $m_model->where(['id'=>intval($uid)])->find();
        $total_money = $order_model->field('sum(money) as total_money')->where(['type'=>1,'uid'=>intval($uid),'status'=>['>',1],'delete_time'=> ['EXP', 'IS NULL']])->find();
        $filed =  'or.id,or.uid,p.project_name,m.username,m.mobile,or.money,p.has_authorize';
        $lists =$order_model->alias('or')
            ->join('member m','m.id=or.uid')
            ->join('project p','p.id=or.project_id')
            ->where(['or.type'=>1,'or.uid'=>intval($uid),'or.status'=>['>',1],'or.delete_time'=> ['EXP', 'IS NULL']])
            ->field($filed)
            ->order('or.id asc')
            ->paginate('', false, page_param());

        if(input('get.down')){
            $filed = 'or.id,p.project_name,m.username,m.mobile,or.money';
            $lists =$order_model->alias('or')
                ->join('member m','m.id=or.uid')
                ->join('project p','p.id=or.project_id')
                ->where(['or.type'=>1,'or.uid'=>intval($uid),'or.status'=>['>',1],'or.delete_time'=> ['EXP', 'IS NULL']])
                ->field($filed)
                ->order('or.id asc')
                ->select();
            $tableHeader = ['项目名称','姓名','手机号','认投金额'];
            $data = [];
            foreach($lists as $k=>$v){
                $data[$k]['project_name'] =  $v['project_name'];
                $data[$k]['username'] =  $v['username'];
                $data[$k]['mobile'] =  $v['mobile'];
                $data[$k]['money'] =  $v['money'];
            }
            ToPHPEXECL($tableHeader,$data,'订单详情');
        }else{
            $this->assign('user_info',$user_info);
            $this->assign('dataList', $lists);
            $this->assign('total_money', empty($total_money['total_money']) ? 0 :$total_money['total_money']);
            return $this->fetch();
        }

    }



    //会员订单变更记录
    public  function memberOrderChange($uid){
        $order_model = new OrderChangeLog();
        $m_model = new \app\admin\model\Member();
        $user_info = $m_model->where(['id'=>intval($uid)])->find();
        $filed =  'p.project_name,m.username,m.mobile,or.money,or.create_time ,or.type,m1.username as from_username,m1.mobile as from_mobile';
        $lists =$order_model->alias('or')
            ->join('member m','m.id=or.user_id')
            ->join('member m1','m1.id=or.re_user_id')
            ->join('project p','p.id=or.project_id')
            ->where(['or.user_id'=>intval($uid)])
            ->field($filed)
            ->order('or.id asc')
            ->paginate('', false, page_param());

        if(input('get.down')){
            $filed = 'p.project_name,m.username,m.mobile,or.money,or.create_time,or.type,m1.username as from_username,m1.mobile as from_mobile';
            $lists =$order_model->alias('or')
                ->join('member m','m.id=or.user_id')
                ->join('member m1','m1.id=or.re_user_id')
                ->join('project p','p.id=or.project_id')
                ->where(['or.user_id'=>intval($uid)])
                ->field($filed)
                ->order('or.id asc')
                ->select();
            $tableHeader = ['项目名称','姓名','手机号','认投金额','变更时间','类型','对象姓名','对象账号'];
            $data = [];
            foreach($lists as $k=>$v){
                $data[$k]['project_name'] =  $v['project_name'];
                $data[$k]['username'] =  $v['username'];
                $data[$k]['mobile'] =  $v['mobile'];
                $data[$k]['money'] =  $v['money'];
                $data[$k]['time'] =  $v['create_time'];
                if($v['type']>1){
                    $data[$k]['type'] = '收入';
                }else{
                    $data[$k]['type'] = '支出';
                }
                $data[$k]['from_username'] =  $v['from_username'];
                $data[$k]['from_mobile'] =  $v['from_mobile'];
            }
            ToPHPEXECL($tableHeader,$data,'订单变更记录');
        }else{
            $this->assign('user_info',$user_info);
            $this->assign('dataList', $lists);
            return $this->fetch();
        }

    }

    //会员订单变更页面信息
    public  function memberOrderChangeInfo($order_id,$uid){
        $order_model = new Order();
        $m_model = new \app\admin\model\Member();
        $user_info = $m_model->where(['id'=>intval($uid)])->find();
        $total_money = $order_model->field('sum(money) as total_money')->where(['type'=>1,'uid'=>intval($uid),'status'=>['>',1]])->find();
        $filed = 'p.project_name,or.money';
        $order_info =$order_model->alias('or')
            ->join('project p','p.id=or.project_id')
            ->where(['or.id'=>intval($order_id)])
            ->field($filed)
            ->find();
        $this->assign('user_info',$user_info);
        $this->assign('order_id', $order_id);
        $this->assign('order_info', $order_info);
        $this->assign('total_money', empty($total_money['total_money']) ? 0 :$total_money['total_money']);
        return $this->fetch();


    }

    //会员订单变更
    public  function orderChange(){
        if(request()->isAjax()){
            $model = new OrderChangeLog();
            $order_model = new Order();
            $member_model = new \app\admin\model\Member();
            $order_id = trim($_POST['order_id']);
            $mobile = trim($_POST['mobile']);
            if($order_id  && $mobile){
                $user_info = $member_model->where(['mobile'=>$mobile])->find();
                if(empty($user_info)){
                    ajaxReturn('未查询到相关会员信息');
                }
                $order_info = $order_model->where(['id'=>intval($order_id)])->find();
                if(empty($order_info)){
                    ajaxReturn('未查询到相关订单信息');
                }
                $data[0]['user_id']=$order_info['uid'];
                $data[0]['re_user_id']=$user_info['id'];
                $data[0]['type']=1;
                $data[0]['money']=$order_info['money'];
                $data[0]['project_id']=$order_info['project_id'];
                $data[0]['order_id']=$order_info['id'];
                $data[0]['create_time']=time();
                $data[0]['update_time']=time();
                $data[1]['user_id']=$user_info['id'];
                $data[1]['re_user_id']=$order_info['uid'];
                $data[1]['type']=2;
                $data[1]['money']=$order_info['money'];
                $data[1]['project_id']=$order_info['project_id'];
                $data[1]['order_id']=$order_info['id'];
                $data[1]['create_time']=time();
                $data[1]['update_time']=time();
                $model->insertAll($data);
                $order_model->where(['id'=>intval($order_id)])->update(['uid'=>intval($user_info['id']),'from_user_id'=>intval($order_info['uid'])]);
                ajaxReturn('变更成功',url('/member/memberOrderDetailList/uid/'.$order_info['uid']));
            }else{
                ajaxReturn('参数错误');
            }


        }else{
            ajaxReturn('请求失败');
        }


    }






}